
package com.jf.cloud.discount.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.jf.cloud.common.cache.constant.CacheNames;
import com.jf.cloud.common.cache.util.RedisUtil;
import com.jf.cloud.discount.mapper.DiscountMapper;
import com.jf.cloud.discount.service.DiscountService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zz
 */
@Component
public class DiscountTask {

    @Autowired
    private DiscountService discountService;
    @Autowired
    private DiscountMapper discountMapper;

    /**
     * 关闭已经结束的满减折活动
     */
    @XxlJob("closeDiscount")
    public void closeDiscount() {
        discountService.closeDiscountBySetStatus();
    }

    /**
     * 满减活动开启，删除商家活动缓存
     * 0 0 0/1 * * ?
     */
    @XxlJob("startDiscount")
    public void startDiscount() {
        // 如果有活动在这个整点开始才去清除缓存
        List<Long> shopIds = discountMapper.listShopIdsWhichStart(DateUtil.beginOfHour(new Date()));
        if (CollUtil.isNotEmpty(shopIds)) {
            // 清除缓存
            List<String> keys = new ArrayList<>();
            for (Long shopId : shopIds) {
                keys.add(CacheNames.DISCOUNT_BY_SHOPID + CacheNames.UNION + shopId);
            }
            RedisUtil.deleteBatch(keys);
        }
    }
}
